import React, { useState } from 'react';
import { 
  Table, 
  Button, 
  Input, 
  Space, 
  message, 
  Popconfirm, 
  Select,
  DatePicker
} from 'antd';
import type { Dayjs } from 'dayjs';
import { 
  SearchOutlined
} from '@ant-design/icons';
import type { ColumnsType } from 'antd/es/table';
import CommonFormModal from '../../components/CommonFormModal';
import { useFormModal } from '../../hooks/useFormModal';
import { departmentFormConfig } from '../../utils/formConfigs';

const { Option } = Select;
const { RangePicker } = DatePicker;

interface Department {
  id: string;
  departmentCode: string;
  departmentName: string;
  creator: string;
  createTime: string;
  modifier: string;
  modifyTime: string;
}

const Department: React.FC = () => {
  // 根据图片描述生成模拟数据
  const [departments, setDepartments] = useState<Department[]>([
    {
      id: '01',
      departmentCode: '1020',
      departmentName: '技术部',
      creator: 'admin',
      createTime: '2021-01-22',
      modifier: 'admin',
      modifyTime: '2020-10-22'
    },
    {
      id: '01',
      departmentCode: '1021',
      departmentName: '仓储部',
      creator: 'admin',
      createTime: '2021-01-22',
      modifier: 'zhangsan',
      modifyTime: '2020-10-22'
    },
    {
      id: '01',
      departmentCode: '1022',
      departmentName: '运营部',
      creator: 'admin',
      createTime: '2021-01-19',
      modifier: 'admin2',
      modifyTime: '2020-10-22'
    },
    {
      id: '01',
      departmentCode: '1023',
      departmentName: '操作部',
      creator: 'admin',
      createTime: '2021-01-19',
      modifier: 'admin1',
      modifyTime: '2020-10-22'
    },
    {
      id: '01',
      departmentCode: '1024',
      departmentName: '办公室',
      creator: 'admin',
      createTime: '2021-01-19',
      modifier: 'admin',
      modifyTime: '2020-10-22'
    }
  ]);

  const [searchText, setSearchText] = useState('');
  const [selectedDepartment, setSelectedDepartment] = useState<string>('');
  const [dateRange, setDateRange] = useState<[Dayjs, Dayjs] | null>(null);
  const [selectedRowKeys, setSelectedRowKeys] = useState<React.Key[]>([]);

  // 使用通用表单Hook
  const {
    visible,
    isAddMode,
    currentRecord,
    loading,
    openAddModal,
    openEditModal,
    closeModal,
  } = useFormModal<Department>();

  const columns: ColumnsType<Department> = [
    {
      title: 'id',
      dataIndex: 'id',
      key: 'id',
      width: 60,
    },
    {
      title: '部门编码',
      dataIndex: 'departmentCode',
      key: 'departmentCode',
      width: 100,
    },
    {
      title: '部门名称',
      dataIndex: 'departmentName',
      key: 'departmentName',
      width: 120,
    },
    {
      title: '创建人',
      dataIndex: 'creator',
      key: 'creator',
      width: 100,
    },
    {
      title: '创建时间',
      dataIndex: 'createTime',
      key: 'createTime',
      width: 120,
    },
    {
      title: '修改人',
      dataIndex: 'modifier',
      key: 'modifier',
      width: 100,
    },
    {
      title: '修改时间',
      dataIndex: 'modifyTime',
      key: 'modifyTime',
      width: 120,
    },
    {
      title: '操作',
      key: 'action',
      width: 120,
      render: (_, record: Department) => (
        <Space size="small">
          <Button 
            type="link" 
            size="small"
            onClick={() => handleEdit(record)}
            style={{ padding: 0, color: '#1890ff' }}
          >
            编辑
          </Button>
          <Popconfirm
            title="确定要删除这个部门吗？"
            onConfirm={() => handleDelete(record.id)}
            okText="确定"
            cancelText="取消"
          >
            <Button 
              type="link" 
              danger 
              size="small"
              style={{ padding: 0 }}
            >
              删除
            </Button>
          </Popconfirm>
        </Space>
      ),
    },
  ];

  const handleAdd = () => {
    openAddModal();
  };

  const handleEdit = (department: Department) => {
    openEditModal(department);
  };

  const handleDelete = (id: string) => {
    setDepartments(departments.filter(dept => dept.id !== id));
    message.success('删除成功');
  };

  const handleSubmit = async (values: Record<string, unknown>, isAddMode: boolean, currentRecord?: Department | null) => {
    if (isAddMode) {
      // 添加部门
      const newDepartment: Department = {
        id: '01',
        departmentCode: values.departmentCode as string,
        departmentName: values.departmentName as string,
        creator: values.creator as string,
        createTime: new Date().toISOString().split('T')[0],
        modifier: values.modifier as string,
        modifyTime: new Date().toISOString().split('T')[0]
      };
      setDepartments([...departments, newDepartment]);
      message.success('部门添加成功');
    } else {
      // 编辑部门
      if (currentRecord) {
        setDepartments(departments.map(dept => 
          dept.id === currentRecord.id 
            ? { ...dept, ...values, modifyTime: new Date().toISOString().split('T')[0] }
            : dept
        ));
        message.success('部门更新成功');
      }
    }
  };

  const handleSearch = () => {
    // 这里可以实现搜索逻辑
    console.log('搜索:', { searchText, selectedDepartment, dateRange });
  };

  const handleReset = () => {
    setSearchText('');
    setSelectedDepartment('');
    setDateRange(null);
  };

  // 过滤后的部门数据
  const filteredDepartments = departments.filter(dept => {
    const matchesSearch = !searchText || 
      dept.departmentName.toLowerCase().includes(searchText.toLowerCase()) ||
      dept.departmentCode.includes(searchText) ||
      dept.creator.toLowerCase().includes(searchText.toLowerCase());
    
    const matchesDepartment = !selectedDepartment || dept.departmentName === selectedDepartment;
    
    return matchesSearch && matchesDepartment;
  });

  const rowSelection = {
    selectedRowKeys,
    onChange: (selectedRowKeys: React.Key[]) => {
      setSelectedRowKeys(selectedRowKeys);
    },
    getCheckboxProps: (record: Department) => ({
      name: record.departmentName,
    }),
  };

  return (
    <div style={{ padding: "20px", height: "calc(100vh - 64px)", overflow: "hidden" }}>
      {/* 搜索区域 */}
      <div
        style={{ 
          backgroundColor: "#fff",
          padding: "20px", 
          marginBottom: "20px",
          borderRadius: "4px"
        }}
      >
        <Input
          placeholder="请输入"
          value={searchText}
          onChange={(e) => setSearchText(e.target.value)}
          style={{ width: 200, marginRight: 16 }}
          suffix={<SearchOutlined />}
        />
        <Select
          placeholder="请选择部门"
          value={selectedDepartment}
          onChange={setSelectedDepartment}
          allowClear
          style={{ width: 200, marginRight: 16 }}
        >
          <Option value="技术部">技术部</Option>
          <Option value="仓储部">仓储部</Option>
          <Option value="运营部">运营部</Option>
          <Option value="操作部">操作部</Option>
          <Option value="办公室">办公室</Option>
        </Select>
        <RangePicker
          placeholder={['加入时间 起始日期', '结束日期']}
          value={dateRange}
          onChange={(dates) => setDateRange(dates as [Dayjs, Dayjs] | null)}
          style={{ width: 300, marginRight: "auto" }}
        />
        <Button
          type="primary"
          style={{ marginRight: 8 }}
          onClick={handleSearch}
        >
          搜索
        </Button>
        <Button onClick={handleReset}>重置</Button>
      </div>

      {/* 按钮区域 */}
      <div style={{ marginBottom: "24px", display: "flex" }}>
        <Button onClick={handleAdd}>
          新增部门
        </Button>
      </div>

      {/* 表格区域 */}
      <Table
        columns={columns}
        dataSource={filteredDepartments}
        rowKey={(record) => `${record.id}-${record.departmentCode}`}
        rowSelection={rowSelection}
        bordered
        pagination={{
          total: filteredDepartments.length,
          pageSize: 10,
          showSizeChanger: true,
          showQuickJumper: true,
          showTotal: (total, range) => 
            `第 ${range[0]}-${range[1]} 条/共 ${total} 条`,
          pageSizeOptions: ['10', '20', '50', '100'],
          size: 'default',
          showLessItems: false,
          itemRender: (page, type, originalElement) => {
            if (type === 'prev') {
              return <Button size="small">‹</Button>;
            }
            if (type === 'next') {
              return <Button size="small">›</Button>;
            }
            if (type === 'jump-prev' || type === 'jump-next') {
              return <span>...</span>;
            }
            return originalElement;
          },
          showTitle: false,
        }}
        scroll={{ x: 1000, y: "calc(100vh - 500px)" }}
        />

      <CommonFormModal
        visible={visible}
        title={isAddMode ? "新增部门" : "编辑部门"}
        isAddMode={isAddMode}
        currentRecord={currentRecord}
        formItems={departmentFormConfig}
        onSubmit={handleSubmit}
        onCancel={closeModal}
        loading={loading}
        width={600}
      />
    </div>
  );
};

export default Department;